<template>
  <a-modal title="选择转化追踪" v-model:visible="visible" width="1000px" @ok="save">
    <AccountTemplate @update:active="accountChange">
      <template #default="{ active }">
        <a-button type="primary" @click="addConversion">
          <template #icon><plus-outlined /></template>
          新建转化追踪
        </a-button>
        <a-button @click="refreshConversionList">
          <template #icon><reload-outlined /></template>
          刷新
        </a-button>
        <div v-if="loading" class="loading-container">
          <a-spin />
        </div>
        <a-table
          v-else
          :columns="conversionColumns"
          :dataSource="conversionList"
          rowKey="conversionId"
          :pagination="false"
          :rowSelection="{
            type: 'radio',
            selectedRowKeys: currentAccountSelectedKeys,
            preserveSelectedRowKeys: true,
            onChange: onSelectChange,
          }"
        ></a-table>
      </template>
    </AccountTemplate>
    <AddConversionModal ref="addConversionModalRef" />
  </a-modal>
</template>

<script setup lang="ts">
import { ref, provide, computed } from "vue";
import AccountTemplate from "@/pages/NewBatchCreateAd/components/common/MultiAccountTemplate.vue";
import { queryConversions } from "@/api/adx-tool";
import { conversionColumns } from "@/pages/NewBatchCreateAd/adx/xiaomi/enum";
import { batchCreateAdStore } from "@/pages/NewBatchCreateAd/store/batchCreateAdStore";
import AddConversionModal from "./AddConversionModal.vue";
import _ from "lodash";
import { message } from "ant-design-vue";
const store = batchCreateAdStore();
const { AccountItems } = store;
provide("accounts", AccountItems);

const visible = ref(false);

const addConversionModalRef = ref();

const emit = defineEmits(["update:visible"]);

const accountIdIndex = ref(0);
const loading = ref(false);
// 计算账号id
const accountId = computed(() => {
  return AccountItems && AccountItems.length > 0 ? AccountItems[accountIdIndex.value]?._id : undefined;
});
const accountChange = (index: number) => {
  accountIdIndex.value = index;
  requestData();
};
// 使用map保存列表数据
const accountConversionsMap: any = ref(new Map());

// 请求数据
const requestData = () => {
  if (!accountConversionsMap.value.has(accountId.value)) {
    loading.value = true;
    queryConversions({
      AccountId: accountId.value,
      extParam: {
        conversionSource: 1,
        conversionType: 1,
      },
    })
      .then((res) => {
        accountConversionsMap.value.set(accountId.value, res);
      })
      .catch(() => {})
      .finally(() => {
        loading.value = false;
      });
  }
};
requestData();

// 计算转化列表
const conversionList = computed(() => {
  return accountConversionsMap.value.get(accountId.value);
});

// 保存账号已选转化追踪 {账号id: {转化追踪}}
const obj = store.Plan && store.Plan.conversionsMap ? store.Plan.conversionsMap : {};
const conversionsMap: any = ref(_.cloneDeep(obj));

// 判断obj和账号的id是否对应，不对应则删除该key
Object.keys(obj).forEach((key: any) => {
  if (!AccountItems.some((account: any) => account._id == key)) {
    delete conversionsMap.value[key];
  }
});

// 循环账号，先判断是否有转换追踪，没有则给所有账号的转换追踪设置为空
AccountItems.forEach((account: any) => {
  if (!conversionsMap.value[account._id]) {
    conversionsMap.value[account._id] = null;
  }
});

// 当前账号已选转化追踪的ID
const currentAccountSelectedKeys = computed(() => {
  if (!accountId.value) return [];

  // 获取当前账号已选择的转化追踪
  const selectedConversion = conversionsMap.value[accountId.value];

  // 如果当前账号有选中的转化追踪，返回其ID
  return selectedConversion ? [selectedConversion.conversionId] : [];
});

// 处理转化追踪选择
const onSelectChange = (_: any, selectedRows: any[]) => {
  if (!accountId.value) return;

  // 移除当前账号中已有的转化追踪
  if (selectedRows.length > 0) {
    const selectedRow = { ...selectedRows[0] }; // 单选模式下只取第一个，创建副本

    // 保存选中的转化追踪
    conversionsMap.value[accountId.value] = selectedRow;

    // 更新当前账号的转化追踪列表中的选中状态
    if (accountConversionsMap.value.has(accountId.value)) {
      const currentList = accountConversionsMap.value.get(accountId.value);
      if (Array.isArray(currentList)) {
        currentList.forEach((item) => {
          item.selected = item.conversionId === selectedRow.conversionId;
        });
      }
    }
  } else {
    // 如果没有选中任何行，则清除当前账号的选择
    delete conversionsMap.value[accountId.value];
  }
};

// 刷新转化追踪列表
const refreshConversionList = () => {
  if (!accountId.value) return;
  // 重新加载当前账号的转化追踪列表
  loading.value = true;
  accountConversionsMap.value.delete(accountId.value);
  requestData();
};

// 新建转化追踪
const addConversion = () => {
  console.log("新建转化追踪");
  addConversionModalRef.value.show();
};

// 保存选择的转化追踪
const save = () => {
  // 判断是否有账号未选择转换追踪
  const hasAccountNotSelectedConversion = Object.keys(conversionsMap.value).some((key) => {
    return !conversionsMap.value[key];
  });
  if (hasAccountNotSelectedConversion) {
    // 找出所有为设置转化追踪的账号名称
    const accountNames = AccountItems.filter((account: any) => !conversionsMap.value[account._id]).map((account: any) => account.Name);
    message.error(`请为以下账号选择转化追踪: ${accountNames.join(", ")}`);
    return;
  }

  store.Plan.conversionsMap = conversionsMap.value;
  visible.value = false;
};

// 导出给父组件使用的方法
const show = () => {
  visible.value = true;
};
defineExpose({
  show,
});
</script>

<style scoped lang="less"></style>
